<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>django 用户模型翻译 | Cucy的博客</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="django">
    <meta name="description" content="django用户认证django默认提供用户认证系统，它提供用户账号，组，权限，cookie，用户session等功能，此文档解释了django如何实现这些功能,此外也介绍如何在项目中自定义用户认证系统 extend and customize 
概述django处理用户验证和授权.简而言之，身份验证如何证明我是我，授权是用户有什么权限。
认证系统包括：

用户
权限: (yes/no)标志，指定">
<meta property="og:type" content="article">
<meta property="og:title" content="django 用户模型翻译">
<meta property="og:url" content="http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/index.html">
<meta property="og:site_name" content="Cucy的博客">
<meta property="og:description" content="django用户认证django默认提供用户认证系统，它提供用户账号，组，权限，cookie，用户session等功能，此文档解释了django如何实现这些功能,此外也介绍如何在项目中自定义用户认证系统 extend and customize 
概述django处理用户验证和授权.简而言之，身份验证如何证明我是我，授权是用户有什么权限。
认证系统包括：

用户
权限: (yes/no)标志，指定">
<meta property="og:updated_time" content="2019-02-22T05:28:07.829Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="django 用户模型翻译">
<meta name="twitter:description" content="django用户认证django默认提供用户认证系统，它提供用户账号，组，权限，cookie，用户session等功能，此文档解释了django如何实现这些功能,此外也介绍如何在项目中自定义用户认证系统 extend and customize 
概述django处理用户验证和授权.简而言之，身份验证如何证明我是我，授权是用户有什么权限。
认证系统包括：

用户
权限: (yes/no)标志，指定">
    
        <link rel="alternate" type="application/atom+xml" title="Cucy的博客" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.6.13">
    <script>window.lazyScripts=[]</script>

    <!-- custom head -->
    

</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.png">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">cucy</h5>
          <a href="mailto:292016176@qq.com" title="292016176@qq.com" class="mail">292016176@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                Archives
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                Tags
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/cucy" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">django 用户模型翻译</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">django 用户模型翻译</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-09-08T07:06:35.000Z" itemprop="datePublished" class="page-time">
  2017-09-08
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#django用户认证"><span class="post-toc-number">1.</span> <span class="post-toc-text">django用户认证</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#概述"><span class="post-toc-number">1.1.</span> <span class="post-toc-text">概述</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#安装"><span class="post-toc-number">1.2.</span> <span class="post-toc-text">安装</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Usage"><span class="post-toc-number">1.3.</span> <span class="post-toc-text">Usage</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#Using-the-Django-authentication-system¶"><span class="post-toc-number">2.</span> <span class="post-toc-text">Using the Django authentication system¶</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#User-objects¶"><span class="post-toc-number">2.1.</span> <span class="post-toc-text">User objects¶</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Creating-users¶"><span class="post-toc-number">2.1.1.</span> <span class="post-toc-text">Creating users¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Creating-superusers¶"><span class="post-toc-number">2.1.2.</span> <span class="post-toc-text">Creating superusers¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Changing-passwords¶"><span class="post-toc-number">2.1.3.</span> <span class="post-toc-text">Changing passwords¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Authenticating-users¶"><span class="post-toc-number">2.1.4.</span> <span class="post-toc-text">Authenticating users¶</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Permissions-and-Authorization¶"><span class="post-toc-number">2.2.</span> <span class="post-toc-text">Permissions and Authorization¶</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Default-permissions¶"><span class="post-toc-number">2.2.1.</span> <span class="post-toc-text">Default permissions¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Groups¶"><span class="post-toc-number">2.2.2.</span> <span class="post-toc-text">Groups¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Programmatically-creating-permissions¶"><span class="post-toc-number">2.2.3.</span> <span class="post-toc-text">Programmatically creating permissions¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Permission-caching¶"><span class="post-toc-number">2.2.4.</span> <span class="post-toc-text">Permission caching¶</span></a></li></ol></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#Authentication-in-Web-requests¶"><span class="post-toc-number">2.3.</span> <span class="post-toc-text">Authentication in Web requests¶</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#How-to-log-a-user-in¶"><span class="post-toc-number">2.3.1.</span> <span class="post-toc-text">How to log a user in¶</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#Selecting-the-authentication-backend¶"><span class="post-toc-number">2.3.1.1.</span> <span class="post-toc-text">Selecting the authentication backend¶</span></a></li></ol></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#How-to-log-a-user-out¶"><span class="post-toc-number">2.3.2.</span> <span class="post-toc-text">How to log a user out¶</span></a></li><li class="post-toc-item post-toc-level-3"><a class="post-toc-link" href="#Limiting-access-to-logged-in-users¶"><span class="post-toc-number">2.3.3.</span> <span class="post-toc-text">Limiting access to logged-in users¶</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#The-raw-way¶"><span class="post-toc-number">2.3.3.1.</span> <span class="post-toc-text">The raw way¶</span></a></li></ol></li></ol></li></ol></li></ol>
        </nav>
    </aside>
    
<article id="post-46-django-用户模型翻译"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">django 用户模型翻译</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-09-08 15:06:35" datetime="2017-09-08T07:06:35.000Z"  itemprop="datePublished">2017-09-08</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <h1 id="django用户认证"><a href="#django用户认证" class="headerlink" title="django用户认证"></a>django用户认证</h1><p>django默认提供用户认证系统，它提供<code>用户账号</code>，<code>组</code>，<code>权限</code>，<code>cookie</code>，<code>用户session</code>等功能，此文档解释了django如何实现这些功能,此外也介绍如何在项目中自定义用户认证系统 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/customizing/" target="_blank" rel="external">extend and customize</a> </p>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>django处理用户验证和授权.简而言之，身份验证如何证明我是我，授权是用户有什么权限。</p>
<p>认证系统包括：</p>
<ul>
<li>用户</li>
<li>权限: (yes/no)标志，指定用户是否可通过检查，可以执行某些操作</li>
<li>组: 组和app关联，用户添加到组中，交集判断用户是否有权限</li>
<li>密码加密系统(hashing)</li>
<li>Forms view logging user 用户表单,视图，限制返回内容等</li>
<li>可插拔后台系统</li>
</ul>
<p>django认证系统是通用系统,不提供web认证系统一些特点，已有第三app已实现</p>
<ul>
<li>Password strength checking 密码强度检查</li>
<li>Throttling of login attempts 登录尝试</li>
<li>Authentication against third-parties (OAuth, for example) 第三方认证系统</li>
</ul>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><p>启用用户权限功能需要在以下安装组件提供相对应的功能<code>django.contrib.auth</code>，默认以安装<code>django-admin startproject</code>启动的时候，已将这些功能安装在<code>INSTALLED_APPS</code>设定中</p>
<ul>
<li><code>&#39;django.contrib.auth&#39;</code> 包含核心认证框架，以及默认的model</li>
<li><code>&#39;django.contrib.contenttypes&#39;</code> 创建权限和user model关联<br>中间件设定<a href="https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-MIDDLEWARE" target="_blank" rel="external"><code>MIDDLEWARE</code></a> :</li>
<li><ol>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/middleware/#django.contrib.sessions.middleware.SessionMiddleware" target="_blank" rel="external"><code>SessionMiddleware</code></a> manages <a href="https://docs.djangoproject.com/en/1.11/topics/http/sessions/" target="_blank" rel="external">sessions</a> across requests.</li>
</ol>
</li>
<li><ol start="2">
<li><a href="https://docs.djangoproject.com/en/1.11/ref/middleware/#django.contrib.auth.middleware.AuthenticationMiddleware" target="_blank" rel="external"><code>AuthenticationMiddleware</code></a> associates users with requests using sessions.</li>
</ol>
</li>
</ul>
<h2 id="Usage"><a href="#Usage" class="headerlink" title="Usage"></a>Usage</h2><p><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/" target="_blank" rel="external">django默认已经实现</a></p>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#user-objects" target="_blank" rel="external">Working with User objects</a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#topic-authorization" target="_blank" rel="external">Permissions and authorization</a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#auth-web-requests" target="_blank" rel="external">Authentication in web requests</a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#auth-admin" target="_blank" rel="external">Managing users in the admin</a></li>
</ul>
<p><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/" target="_blank" rel="external">API reference for the default implementation</a></p>
<p><a href="https://docs.djangoproject.com/en/1.11/topics/auth/customizing/" target="_blank" rel="external">Customizing Users and authentication</a></p>
<p><a href="https://docs.djangoproject.com/en/1.11/topics/auth/passwords/" target="_blank" rel="external">Password management in Django</a></p>
<h1 id="Using-the-Django-authentication-system¶"><a href="#Using-the-Django-authentication-system¶" class="headerlink" title="Using the Django authentication system¶"></a>Using the Django authentication system<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#using-the-django-authentication-system" target="_blank" rel="external">¶</a></h1><p>本文档适用于配置了django默认的认证系统,适用于很多常见的用户验证项目，权限和密码权限等需求。亦可进行自行扩展 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/customizing/" target="_blank" rel="external">extension and customization</a>认证系统.</p>
<p>django提供了认证和授权,一般称为认证系统,功能有些耦合</p>
<h2 id="User-objects¶"><a href="#User-objects¶" class="headerlink" title="User objects¶"></a><code>User</code> objects<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#user-objects" target="_blank" rel="external">¶</a></h2><p><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a>用户对象时身份验证系统的核心。 用户有自身的基本属性(个人详情信息)，通过这些属性信息集合django认证的框架，以达到<code>管理</code>和<code>普通用户</code>不同类的对象</p>
<p>主要有以下属性:</p>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.username" target="_blank" rel="external"><code>username</code></a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.password" target="_blank" rel="external"><code>password</code></a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.email" target="_blank" rel="external"><code>email</code></a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.first_name" target="_blank" rel="external"><code>first_name</code></a></li>
<li><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.last_name" target="_blank" rel="external"><code>last_name</code></a></li>
</ul>
<p>See the <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>full API documentation</code></a> for full reference, the documentation that follows is more task oriented.</p>
<h3 id="Creating-users¶"><a href="#Creating-users¶" class="headerlink" title="Creating users¶"></a>Creating users<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#creating-users" target="_blank" rel="external">¶</a></h3><p>The most direct way to create users is to use the included <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.UserManager.create_user" target="_blank" rel="external"><code>create_user()</code></a> helper function 直接创建用户的函数:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> django.contrib.auth.models <span class="keyword">import</span> User</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>user = User.objects.create_user(<span class="string">'john'</span>, <span class="string">'lennon@thebeatles.com'</span>, <span class="string">'johnpassword'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># At this point, user is a User object that has already been saved</span></span><br><span class="line"><span class="comment"># to the database. You can continue to change its attributes</span></span><br><span class="line"><span class="comment"># if you want to change other fields. 修改字段需要手动提交保存</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>user.last_name = <span class="string">'Lennon'</span></span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>user.save()</span><br></pre></td></tr></table></figure>
<p>另一种创建用户的方法。If you have the Django admin installed, you can also <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#auth-admin" target="_blank" rel="external">create users interactively</a>.</p>
<h3 id="Creating-superusers¶"><a href="#Creating-superusers¶" class="headerlink" title="Creating superusers¶"></a>Creating superusers<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#creating-superusers" target="_blank" rel="external">¶</a></h3><p>创建管理员命令 <a href="https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-createsuperuser" target="_blank" rel="external"><code>createsuperuser</code></a> :</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">$ python manage.py createsuperuser --username=joe --email=joe@example.com</span><br></pre></td></tr></table></figure>
<p>输入以上命令后 <a href="https://docs.djangoproject.com/en/1.11/ref/django-admin/#cmdoption-createsuperuser-username" target="_blank" rel="external"><code>--username</code></a> or <a href="https://docs.djangoproject.com/en/1.11/ref/django-admin/#cmdoption-createsuperuser-email" target="_blank" rel="external"><code>--email</code></a> 会有输入密码的请求.</p>
<h3 id="Changing-passwords¶"><a href="#Changing-passwords¶" class="headerlink" title="Changing passwords¶"></a>Changing passwords<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#changing-passwords" target="_blank" rel="external">¶</a></h3><p>Django不是以明文存储密码 (clear text)在user model中, 而是hash (see <a href="https://docs.djangoproject.com/en/1.11/topics/auth/passwords/" target="_blank" rel="external">documentation of how passwords are managed</a>因此，不要试图直接操纵用户的密码属性。这就是创建用户时使用辅助函数的原因.</p>
<p>要更改用户的密码，您有几个选项:</p>
<p><a href="https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-changepassword" target="_blank" rel="external"><code>manage.py changepassword *username*</code></a> 提供一种从命令行更改用户密码的方法。它提示您更改给定用户的密码，您必须输入两次密码。如果两者都匹配，则新密码将立即更改。如果不提供用户，则命令将尝试更改用户名与当前登录的系统用户相匹配的密码（当前登录到此系统的用户）</p>
<p>另一种修改密码的方式 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.set_password" target="_blank" rel="external"><code>set_password()</code></a>:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;&gt; </span><span class="keyword">from</span> django.contrib.auth.models <span class="keyword">import</span> User</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>u = User.objects.get(username=<span class="string">'john'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>u.set_password(<span class="string">'new password'</span>)</span><br><span class="line"><span class="meta">&gt;&gt;&gt; </span>u.save()</span><br></pre></td></tr></table></figure>
<p>如果启用了admin后台也可以修改所有用户的密码<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#auth-admin" target="_blank" rel="external">authentication system’s admin pages</a>.</p>
<p>Django也提供 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#built-in-auth-views" target="_blank" rel="external">views</a> and <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#built-in-auth-forms" target="_blank" rel="external">forms</a> 修改用户的密码</p>
<p>修改用户密码后期session信息会失效. 详情查看 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#session-invalidation-on-password-change" target="_blank" rel="external">Session invalidation on password change</a> .</p>
<h3 id="Authenticating-users¶"><a href="#Authenticating-users¶" class="headerlink" title="Authenticating users¶"></a>Authenticating users<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#authenticating-users" target="_blank" rel="external">¶</a></h3><ul>
<li><p><code>authenticate</code>(<em>request=None</em>, *<em>\</em>credentials*)<a href="https://docs.djangoproject.com/en/1.11/_modules/django/contrib/auth/#authenticate" target="_blank" rel="external">[source]</a><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.authenticate" target="_blank" rel="external">¶</a></p>
<p>使用<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.authenticate" target="_blank" rel="external"><code>authenticate()</code></a> 作为验证凭证. 将, <code>username</code> 和<code>password</code> 以关键字传入函数进行验证, 后台会进行检查 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#authentication-backends" target="_blank" rel="external">authentication backend</a>, 返回一个 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a> 对象如果通过检查. 如果验证不通过则抛出异常 <a href="https://docs.djangoproject.com/en/1.11/ref/exceptions/#django.core.exceptions.PermissionDenied" target="_blank" rel="external"><code>PermissionDenied</code></a>, 返回值为 <code>None</code>. For example:</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib.auth <span class="keyword">import</span> authenticate</span><br><span class="line">user = authenticate(username=<span class="string">'john'</span>, password=<span class="string">'secret'</span>)</span><br><span class="line"><span class="keyword">if</span> user <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">    <span class="comment"># A backend authenticated the credentials</span></span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="comment"># No backend authenticated the credentials</span></span><br></pre></td></tr></table></figure>
<p><code>request</code>是一个<a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest" target="_blank" rel="external"><code>HttpRequest</code></a> 生成的对象, 这是通过 <code>authenticate()</code> 后端方法认证</p>
<p>Changed in Django 1.11:</p>
<p>The optional <code>request</code> argument was added.</p>
<h2 id="Permissions-and-Authorization¶"><a href="#Permissions-and-Authorization¶" class="headerlink" title="Permissions and Authorization¶"></a>Permissions and Authorization<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#permissions-and-authorization" target="_blank" rel="external">¶</a></h2><p>Django有一个简单的权限系统。它提供了一种将权限分配给特定用户和用户组的方法。</p>
<p>它是由Django管理后台站点中使用，你也可以用于自己的代码中。</p>
<p>Django管理后台站点使用权限如下：</p>
<ul>
<li>总的来说有三个权限<code>add, change,delete</code></li>
<li>Access to view the “add” form and add an object is limited to users with the “add” permission for that type of object.</li>
<li>Access to view the change list, view the “change” form and change an object is limited to users with the “change” permission for that type of object.</li>
<li>Access to delete an object is limited to users with the “delete” permission for that type of object.</li>
</ul>
<p>权限不仅可以设置每个对象类型，而且可以设置每个特定对象实例。通过使用<a href="https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_add_permission" target="_blank" rel="external"><code>has_add_permission()</code></a>, <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_change_permission" target="_blank" rel="external"><code>has_change_permission()</code></a> and <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.has_delete_permission" target="_blank" rel="external"><code>has_delete_permission()</code></a> 所提供的方法 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin" target="_blank" rel="external"><code>ModelAdmin</code></a> 类, 可以为同一类型的不同对象实例定制权限。</p>
<p><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a> 对象有两个多对多字段: <code>groups</code> 和<code>user_permissions</code>. <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a> 对象可以以与其他方法相同的方式访问它们的相关对象 <a href="https://docs.djangoproject.com/en/1.11/topics/db/models/" target="_blank" rel="external">Django model</a>:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line">myuser.groups.set([group_list])</span><br><span class="line">myuser.groups.add(group, group, ...)</span><br><span class="line">myuser.groups.remove(group, group, ...)</span><br><span class="line">myuser.groups.clear()</span><br><span class="line">myuser.user_permissions.set([permission_list])</span><br><span class="line">myuser.user_permissions.add(permission, permission, ...)</span><br><span class="line">myuser.user_permissions.remove(permission, permission, ...)</span><br><span class="line">myuser.user_permissions.clear()</span><br></pre></td></tr></table></figure>
<h3 id="Default-permissions¶"><a href="#Default-permissions¶" class="headerlink" title="Default permissions¶"></a>Default permissions<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#default-permissions" target="_blank" rel="external">¶</a></h3><p>当<code>django.contrib.auth</code>设定于 <a href="https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS" target="_blank" rel="external"><code>INSTALLED_APPS</code></a> setting中, 它将会三个默认权限 – <code>add, change and delete</code>– 是在你安装的应用程序定义的每个Django模型默认创建.</p>
<p>这些权限将在运行时创建 <a href="https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-migrate" target="_blank" rel="external"><code>manage.py migrate</code></a>; 第一次运行 <code>migrate</code> 在加入<code>django.contrib.auth</code> 到<a href="https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-INSTALLED_APPS" target="_blank" rel="external"><code>INSTALLED_APPS</code></a>, 将为所有以前安装的模型创建默认权限,以及当时安装的任何新model. 然后, 每次运行时，它将为新模型创建默认权限 <a href="https://docs.djangoproject.com/en/1.11/ref/django-admin/#django-admin-migrate" target="_blank" rel="external"><code>manage.py migrate</code></a> (创建权限的函数连接到<a href="https://docs.djangoproject.com/en/1.11/ref/signals/#django.db.models.signals.post_migrate" target="_blank" rel="external"><code>post_migrate</code></a> 信号).</p>
<p>假设您有一个带有 <a href="https://docs.djangoproject.com/en/1.11/ref/models/options/#django.db.models.Options.app_label" target="_blank" rel="external"><code>app_label</code></a> <code>foo</code> 和model名为 <code>Bar</code>, 要测试基本权限，您应该使用:</p>
<ul>
<li>add: <code>user.has_perm(&#39;foo.add_bar&#39;)</code></li>
<li>change: <code>user.has_perm(&#39;foo.change_bar&#39;)</code></li>
<li>delete: <code>user.has_perm(&#39;foo.delete_bar&#39;)</code></li>
</ul>
<p>The <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.Permission" target="_blank" rel="external"><code>Permission</code></a> 很少直接访问模型</p>
<h3 id="Groups¶"><a href="#Groups¶" class="headerlink" title="Groups¶"></a>Groups<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#groups" target="_blank" rel="external">¶</a></h3><p><a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.Group" target="_blank" rel="external"><code>django.contrib.auth.models.Group</code></a> models是对用户进行分类的通用方法，因此您可以应用权限, 或其他标签,哪些用户. 一个用户可以属于一个或多个组.</p>
<p>组中的用户自动拥有授予该组的权限. For example, 如果组 <code>Site editors</code> 有权限 <code>can_edit_home_page</code>, 该组中的任何用户都将获得该权限.</p>
<p>Beyond permissions, 组是一种方便的方法来分类用户给他们一些标签, 或扩展功能<br>. For example, 你可以创建一个组 <code>&#39;Special users&#39;</code>, and you could write code that could, say, give them access to a members-only portion of your site, or send them members-only email messages （组内成员操作）.</p>
<h3 id="Programmatically-creating-permissions¶"><a href="#Programmatically-creating-permissions¶" class="headerlink" title="Programmatically creating permissions¶"></a>Programmatically creating permissions<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#programmatically-creating-permissions" target="_blank" rel="external">¶</a></h3><p>当<a href="https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#custom-permissions" target="_blank" rel="external">custom permissions</a> 可以在模型中定义 <code>Meta</code> 类, 您还可以直接创建权限. For example, you can create the <code>can_publish</code> permission for a <code>BlogPost</code> model in <code>myapp</code>:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> myapp.models <span class="keyword">import</span> BlogPost</span><br><span class="line"><span class="keyword">from</span> django.contrib.auth.models <span class="keyword">import</span> Permission</span><br><span class="line"><span class="keyword">from</span> django.contrib.contenttypes.models <span class="keyword">import</span> ContentType</span><br><span class="line"></span><br><span class="line">content_type = ContentType.objects.get_for_model(BlogPost)</span><br><span class="line">permission = Permission.objects.create(</span><br><span class="line">    codename=<span class="string">'can_publish'</span>,</span><br><span class="line">    name=<span class="string">'Can Publish Posts'</span>,</span><br><span class="line">    content_type=content_type,</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>然后可以将权限分配给 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a> 通过其 <code>user_permissions</code> 属性或 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.Group" target="_blank" rel="external"><code>Group</code></a> 通过其 <code>permissions</code>属性.</p>
<h3 id="Permission-caching¶"><a href="#Permission-caching¶" class="headerlink" title="Permission caching¶"></a>Permission caching<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#permission-caching" target="_blank" rel="external">¶</a></h3><p>The <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.backends.ModelBackend" target="_blank" rel="external"><code>ModelBackend</code></a> 在第一次为权限检查获取用户对象时，对其进行缓存. 对于请求响应周期来说，这通常是很好的，因为在添加权限后，通常不会立即检查权限（例如，在admin后台中）。如果您正在添加权限并立即检查它们, 例如，在测试或视图中, 最简单的解决方案是从数据库中重新获取用户. For example:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib.auth.models <span class="keyword">import</span> Permission, User</span><br><span class="line"><span class="keyword">from</span> django.contrib.contenttypes.models <span class="keyword">import</span> ContentType</span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> get_object_or_404</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> myapp.models <span class="keyword">import</span> BlogPost</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">user_gains_perms</span><span class="params">(request, user_id)</span>:</span></span><br><span class="line">    user = get_object_or_404(User, pk=user_id)</span><br><span class="line">    <span class="comment"># any permission check will cache the current set of permissions</span></span><br><span class="line">    user.has_perm(<span class="string">'myapp.change_blogpost'</span>)</span><br><span class="line"></span><br><span class="line">    content_type = ContentType.objects.get_for_model(BlogPost)</span><br><span class="line">    permission = Permission.objects.get(</span><br><span class="line">        codename=<span class="string">'change_blogpost'</span>,</span><br><span class="line">        content_type=content_type,</span><br><span class="line">    )</span><br><span class="line">    user.user_permissions.add(permission)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Checking the cached permission set</span></span><br><span class="line">    user.has_perm(<span class="string">'myapp.change_blogpost'</span>)  <span class="comment"># False</span></span><br><span class="line"></span><br><span class="line">    <span class="comment"># Request new instance of User</span></span><br><span class="line">    <span class="comment"># Be aware that user.refresh_from_db() won't clear the cache.</span></span><br><span class="line">    user = get_object_or_404(User, pk=user_id)</span><br><span class="line"></span><br><span class="line">    <span class="comment"># Permission cache is repopulated from the database</span></span><br><span class="line">    user.has_perm(<span class="string">'myapp.change_blogpost'</span>)  <span class="comment"># True</span></span><br><span class="line"></span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<h2 id="Authentication-in-Web-requests¶"><a href="#Authentication-in-Web-requests¶" class="headerlink" title="Authentication in Web requests¶"></a>Authentication in Web requests<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#authentication-in-web-requests" target="_blank" rel="external">¶</a></h2><p>Django 使用<a href="https://docs.djangoproject.com/en/1.11/topics/http/sessions/" target="_blank" rel="external">sessions</a> 中间件将认证系统接入 <a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest" target="_blank" rel="external"><code>request objects</code></a>.</p>
<p>这提供一个 <a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest.user" target="_blank" rel="external"><code>request.user</code></a>表示当前用户的每个请求的属性.如果当前用户没有登录，则该属性将被设置为<a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.AnonymousUser" target="_blank" rel="external"><code>AnonymousUser</code></a>, otherwise it will be an instance of <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a>.</p>
<p>你可以把它们区分开来 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated" target="_blank" rel="external"><code>is_authenticated</code></a>, 像这样:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">if</span> request.user.is_authenticated:</span><br><span class="line">    <span class="comment"># Do something for authenticated users.</span></span><br><span class="line">    ...</span><br><span class="line"><span class="keyword">else</span>:</span><br><span class="line">    <span class="comment"># Do something for anonymous users.</span></span><br><span class="line">    ...</span><br></pre></td></tr></table></figure>
<h3 id="How-to-log-a-user-in¶"><a href="#How-to-log-a-user-in¶" class="headerlink" title="How to log a user in¶"></a>How to log a user in<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-in" target="_blank" rel="external">¶</a></h3><p>如果您有一个经过身份验证的用户要附加到当前会话-这是用 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>login()</code></a> 函数.</p>
<ul>
<li><code>login</code>(<em>request</em>, <em>user</em>, <em>backend=None</em>)<a href="https://docs.djangoproject.com/en/1.11/_modules/django/contrib/auth/#login" target="_blank" rel="external">[source]</a><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external">¶</a></li>
</ul>
<p>从视图中记录一个用户已登录, 使用 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>login()</code></a>. 它需要一个 <a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest" target="_blank" rel="external"><code>HttpRequest</code></a> 对象和一个 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User" target="_blank" rel="external"><code>User</code></a> 对象. <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>login()</code></a> 将用户ID保存在会话中, using Django’s session framework.注意，匿名会话中的任何数据集都保留在用户登录后的会话中.这个示例演示了如何使用这两种方法<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.authenticate" target="_blank" rel="external"><code>authenticate()</code></a> 和<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>login()</code></a>:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib.auth <span class="keyword">import</span> authenticate, login</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    username = request.POST[<span class="string">'username'</span>]</span><br><span class="line">    password = request.POST[<span class="string">'password'</span>]</span><br><span class="line">    user = authenticate(request, username=username, password=password)</span><br><span class="line">    <span class="keyword">if</span> user <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</span><br><span class="line">        login(request, user)</span><br><span class="line">        <span class="comment"># Redirect to a success page.</span></span><br><span class="line">        ...</span><br><span class="line">    <span class="keyword">else</span>:</span><br><span class="line">        <span class="comment"># Return an 'invalid login' error message.</span></span><br><span class="line">        ...</span><br></pre></td></tr></table></figure>
<p>Changed in Django 1.10:</p>
<p>在旧版本中，当您手动记录用户时，您必须*成功地验证用户<br><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.authenticate" target="_blank" rel="external"><code>authenticate()</code></a>在调用前 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>login()</code></a>. 现在您可以使用新的后端设置 <code>backend</code> 参数.</p>
<h4 id="Selecting-the-authentication-backend¶"><a href="#Selecting-the-authentication-backend¶" class="headerlink" title="Selecting the authentication backend¶"></a>Selecting the authentication backend<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#selecting-the-authentication-backend" target="_blank" rel="external">¶</a></h4><p>当用户登录时，用户ID和用于身份验证的后端保存在用户会话中。这允许相同的<a href="https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#authentication-backends" target="_blank" rel="external">authentication backend</a> 在将来的请求中获取用户的详细信息. 在会话中保存的身份验证后端选择如下:</p>
<ol>
<li>使用可选项 <code>backend</code> 参数, 如果已设定.</li>
<li>Use the value of the <code>user.backend</code> attribute, 这是目前. 这允许配对<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.authenticate" target="_blank" rel="external"><code>authenticate()</code></a> 和<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>login()</code></a>:<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.authenticate" target="_blank" rel="external"><code>authenticate()</code></a> 集the <code>user.backend</code> attribute on the user object it returns.</li>
<li>Use the <code>backend</code> in <a href="https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-AUTHENTICATION_BACKENDS" target="_blank" rel="external"><code>AUTHENTICATION_BACKENDS</code></a>, if there is only one.</li>
<li>Otherwise, raise an exception.</li>
</ol>
<p>In cases 1 and 2, the value of the <code>backend</code> argument or the <code>user.backend</code> attribute should be a dotted import path string (like that found in <a href="https://docs.djangoproject.com/en/1.11/ref/settings/#std:setting-AUTHENTICATION_BACKENDS" target="_blank" rel="external"><code>AUTHENTICATION_BACKENDS</code></a>), not the actual backend class.</p>
<h3 id="How-to-log-a-user-out¶"><a href="#How-to-log-a-user-out¶" class="headerlink" title="How to log a user out¶"></a>How to log a user out<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#how-to-log-a-user-out" target="_blank" rel="external">¶</a></h3><ul>
<li><p><code>logout</code>(<em>request</em>)<a href="https://docs.djangoproject.com/en/1.11/_modules/django/contrib/auth/#logout" target="_blank" rel="external">[source]</a><a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout" target="_blank" rel="external">¶</a></p>
<p>注销已登录用户 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.login" target="_blank" rel="external"><code>django.contrib.auth.login()</code></a>, 使用<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout" target="_blank" rel="external"><code>django.contrib.auth.logout()</code></a> within your view. 它需要一个 <a href="https://docs.djangoproject.com/en/1.11/ref/request-response/#django.http.HttpRequest" target="_blank" rel="external"><code>HttpRequest</code></a> object and has no return value. Example:</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib.auth <span class="keyword">import</span> logout</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">logout_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    logout(request)</span><br><span class="line">    <span class="comment"># Redirect to a success page.</span></span><br></pre></td></tr></table></figure>
<p>Note that <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout" target="_blank" rel="external"><code>logout()</code></a> 如果用户没有登录不会抛出任何的异常.</p>
<p>当你调用 <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout" target="_blank" rel="external"><code>logout()</code></a>, 当前请求的会话数据已完全清除。所有现有数据都已删除. 这是为了防止另一个人使用同一个Web浏览器登录并访问以前用户的会话数据. 如果您希望在登录后立即向用户可用的会话中放入任何内容, do that <em>after</em> calling <a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.logout" target="_blank" rel="external"><code>django.contrib.auth.logout()</code></a>.</p>
<h3 id="Limiting-access-to-logged-in-users¶"><a href="#Limiting-access-to-logged-in-users¶" class="headerlink" title="Limiting access to logged-in users¶"></a>Limiting access to logged-in users<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#limiting-access-to-logged-in-users" target="_blank" rel="external">¶</a></h3><h4 id="The-raw-way¶"><a href="#The-raw-way¶" class="headerlink" title="The raw way¶"></a>The raw way<a href="https://docs.djangoproject.com/en/1.11/topics/auth/default/#the-raw-way" target="_blank" rel="external">¶</a></h4><p>限制页面访问的简单、原始方法是检查 <a href="https://docs.djangoproject.com/en/1.11/ref/contrib/auth/#django.contrib.auth.models.User.is_authenticated" target="_blank" rel="external"><code>request.user.is_authenticated</code></a> 或者重定向到登录页面:</p>
<figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> django.conf <span class="keyword">import</span> settings</span><br><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> redirect</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> request.user.is_authenticated:</span><br><span class="line">        <span class="keyword">return</span> redirect(<span class="string">'%s?next=%s'</span> % (settings.LOGIN_URL, request.path))</span><br><span class="line">    <span class="comment"># ...</span></span><br></pre></td></tr></table></figure>
<p>…or display an error message:<br><figure class="highlight python"><table><tr><td class="code"><pre><span class="line"><span class="keyword">from</span> django.shortcuts <span class="keyword">import</span> render</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">my_view</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> <span class="keyword">not</span> request.user.is_authenticated:</span><br><span class="line">        <span class="keyword">return</span> render(request, <span class="string">'myapp/login_error.html'</span>)</span><br><span class="line">    <span class="comment"># ...</span></span><br></pre></td></tr></table></figure></p>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2019-02-22T05:28:07.829Z" itemprop="dateUpdated">2019-02-22 13:28:07</time>
</span><br>


        
        <a href="/2017/09/08/46-django-用户模型翻译/" target="_blank" rel="external">http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/</a>
        
    </div>
    <footer>
        <a href="http://zhourudong.cn">
            <img src="/img/avatar.png" alt="cucy">
            cucy
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/django/">django</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/&title=《django 用户模型翻译》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/&title=《django 用户模型翻译》 — Cucy的博客&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《django 用户模型翻译》 — Cucy的博客&url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/09/13/47-django官方文档快捷链接/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">django官方文档快捷链接</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/08/24/45-gitlab维护/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">gitlab维护</h4>
      </a>
    </div>
  
</nav>



    














</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢大爷~
        <i class="icon icon-quote-right"></i>
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/img/wechat.jpg" data-alipay="/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>



</div>

        <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        站点总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        站点总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循 <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p><span>cucy &copy; 2016 - 2021</span>
            <span>
                
                Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a>
            </span>
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/&title=《django 用户模型翻译》 — Cucy的博客&pic=http://zhourudong.cn/img/avatar.png" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/&title=《django 用户模型翻译》 — Cucy的博客&source=" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《django 用户模型翻译》 — Cucy的博客&url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/&via=http://zhourudong.cn" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="//api.qrserver.com/v1/create-qr-code/?data=http://zhourudong.cn/2017/09/08/46-django-用户模型翻译/" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };


</script>

<script src="/js/main.min.js?v=1.6.13"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="/js/search.min.js?v=1.6.13" async></script>






<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
